//
//  TaskManagerListVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/3/19.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "TaskManagerListVC.h"
#import "TaskManagerListModel.h"
#import "TaskManagerListCell.h"
#import "TaskManagerSearchModel.h"
#import "LJInPutTool.h"
#import "TaskManagerDetailVC.h"
#import "OperationBillDiaoDuVC.h"
#import "TaskGuiJiVC.h"
#import "DaoHangVC.h"
#import "AbnormalReportMainVC.h"
#import "HuiDanBackVC.h"

@interface TaskManagerListVC ()<UITableViewDelegate,UITableViewDataSource> {
    int page;
    int boHui_task_id;
    int zuoFei_wa_id;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <TaskManagerListModel *>*dataArray;
@property (nonatomic, strong) LJInPutTool *boHuiInPutTool;//驳回输入框
//@property (nonatomic, strong) LJInPutTool *zuoFeiInPutTool;//作废输入框
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation TaskManagerListVC

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64 - 54 - 40, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [saveBtn setBackgroundColor:HexColorA(0xF35959, 0.1)];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"状态上报" forState:0];
        [saveBtn setTitleColor:HexColor(0xF35959) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(yiChangClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)yiChangClick {
    AbnormalReportMainVC *vc = [AbnormalReportMainVC new];
    vc.isPush = YES;
    vc.sta_id = @"";
    vc.type = 1;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(LJInPutTool *)boHuiInPutTool {
    if (!_boHuiInPutTool) {
        _boHuiInPutTool = [LJInPutTool new];
        __weak_self;
        _boHuiInPutTool.finishBlock = ^(NSString * _Nonnull str) {
            //驳回
            [weakself requestForBoHuiWithReason:str];
        };
    }
    return _boHuiInPutTool;
}

-(NSMutableArray<TaskManagerListModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, [User userIsDriver] ? ScreenH - self.bottomView.nim_height - NaviHeight - 54 - 40 : ScreenH - BottomHeight - NaviHeight - 54 - 40) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.estimatedRowHeight = 0;
//        _tableView.estimatedSectionFooterHeight = 0;
//        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    boHui_task_id = 0;
    zuoFei_wa_id = 0;
    [self.view addSubview:self.tableView];
    if ([User userIsDriver]) {
        [self.view addSubview:self.bottomView];
    }
    [self requestForList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList:) name:ReceiptDeliveryRefreshTaskManagerList object:nil];
}

- (void)refreshList:(NSNotification *)noti {
    if (noti) {
        TaskManagerSearchModel *model = [TaskManagerSearchModel mj_objectWithKeyValues:noti.userInfo];
        if (model) {
            self.searchModel = model;
        }
    }
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.status) {
        [dic setObject:@(self.status) forKey:@"status"];
    }
    if (self.jh_status) {
        [dic setObject:@(self.jh_status) forKey:@"jh_status"];
    }
    [dic setObject:@(page) forKey:@"page"];
    if (self.searchModel.the_num.length) {
        [dic setObject:self.searchModel.the_num forKey:@"the_num"];
    }
    if (self.searchModel.s_city.length) {
        [dic setObject:self.searchModel.s_city forKey:@"s_city"];
    }
    if (self.searchModel.r_city.length) {
        [dic setObject:self.searchModel.r_city forKey:@"r_city"];
    }
    if (self.searchModel.t_name.length) {
        [dic setObject:self.searchModel.t_name forKey:@"t_name"];
    }
    if (self.searchModel.car_require_name.length) {
        [dic setObject:@(self.searchModel.car_require) forKey:@"car_require"];
    }
    if (self.searchModel.pnum_min.length) {
        [dic setObject:self.searchModel.pnum_min forKey:@"pnum_min"];
    }
    if (self.searchModel.pnum_max.length) {
        [dic setObject:self.searchModel.pnum_max forKey:@"pnum_max"];
    }
    if (self.searchModel.weight_min.length) {
        [dic setObject:self.searchModel.weight_min forKey:@"weight_min"];
    }
    if (self.searchModel.weight_max.length) {
        [dic setObject:self.searchModel.weight_max forKey:@"weight_max"];
    }
    if (self.searchModel.volume_min.length) {
        [dic setObject:self.searchModel.volume_min forKey:@"volume_min"];
    }
    if (self.searchModel.volume_max.length) {
        [dic setObject:self.searchModel.volume_max forKey:@"volume_max"];
    }
    if (self.searchModel.strat_time.length) {
        [dic setObject:self.searchModel.strat_time forKey:@"strat_time"];
    }
    if (self.searchModel.end_time.length) {
        [dic setObject:self.searchModel.end_time forKey:@"end_time"];
    }
    [HttpRequest PostWithApi:LogisticsSupplierTaskManagerList params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.dataArray removeAllObjects];
                self.dataArray = [TaskManagerListModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [TaskManagerListModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.dataArray addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerListCell *cell = [TaskManagerListCell TaskManagerListCellWithTableView:tableView];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    cell.model = model;
    __weak_self;
    cell.diaoDuBlock = ^{
        OperationBillDiaoDuVC *vc = [OperationBillDiaoDuVC new];
        vc.sta_id = [model.Id intValue];
        vc.goods_jnum = model.residue_pnum;
        vc.goods_num = model.residue_num;
        vc.goods_weight = model.residue_weight;
        vc.goods_volume = model.residue_volume;
        vc.delivery_address = model.r_city;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.shouHuoBlock = ^{
        TaskManagerDetailVC *vc = [TaskManagerDetailVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.sureBlock = ^{
        [weakself sureClick:model];
    };
    cell.boHuiBlock = ^{
        __strong_self;
        strongSelf->boHui_task_id = [model.Id intValue];
        [weakself rejectClick];
    };
    cell.chuFaBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认出发？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForChuFa:model];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.songHuoChuFaBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认出发？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForChuFa:model];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.guiJiBlock = ^{
        TaskGuiJiVC *vc = [TaskGuiJiVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.YiChangShangBaoBlock = ^{
        AbnormalReportMainVC *vc = [AbnormalReportMainVC new];
        vc.isPush = YES;
        vc.sta_id = model.Id;
        vc.type = 1;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.daoDaBlock = ^{
        TaskManagerDetailVC *vc = [TaskManagerDetailVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.zhuangCheBlock = ^{
        TaskManagerDetailVC *vc = [TaskManagerDetailVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.erWeiMaBlock = ^{
        
    };
    cell.huiDanFanHuiBlock = ^{
        HuiDanBackVC *vc = [HuiDanBackVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

- (void)requestForChuFa:(TaskManagerListModel *)model {
    [HttpRequest PostWithApi:LogisticsSupplierTaskChuFa params:@{@"sta_id":model.Id,@"lat":@([[LJLocationManager shareManager] getCurrentLocation].latitude),@"lng":@([[LJLocationManager shareManager] getCurrentLocation].longitude)} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (model.r_city_lng_lat.count) {
                if (model.r_city_lng_lat.count > 1) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择要导航的地址" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                    [model.r_city_lng_lat enumerateObjectsUsingBlock:^(TaskManagerListAddressLocationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            DaoHangVC *vc = [DaoHangVC new];
                            vc.address = obj.name;
                            vc.lat = obj.lat;
                            vc.lng = obj.lng;
                            [self.rt_navigationController pushViewController:vc animated:YES];
                        }];
                        [alert addAction:action1];
                    }];
                    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                    }];
                    [alert addAction:cancle];
                    [self presentViewController:alert animated:YES completion:nil];
                }else {
                    DaoHangVC *vc = [DaoHangVC new];
                    vc.address = model.r_city_lng_lat.firstObject.name;
                    vc.lat = model.r_city_lng_lat.firstObject.lat;
                    vc.lng = model.r_city_lng_lat.firstObject.lng;
                    [self.rt_navigationController pushViewController:vc animated:YES];
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

//驳回
- (void)rejectClick {
    self.boHuiInPutTool.placeholder = @"请输入驳回原因";
    self.boHuiInPutTool.sureBtnText = @"确认驳回";
    self.boHuiInPutTool.cancleBtnText = @"取消驳回";
    [self.boHuiInPutTool showInView:MAIN_WINDOW];
}

- (void)sureClick:(TaskManagerListModel *)model {
    if (model.is_receie == 1) {
        //未完成，显示收货，要选择仓库
        if (model.sup_address.count) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            [model.sup_address enumerateObjectsUsingBlock:^(TaskManagerListAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.info style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self requestForOperationWithStatus:1 withSta_id:model.Id withCk_id:obj.Id];
                }];
                [alert addAction:action1];
            }];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

            }];
            [alert addAction:cancle];
            [self presentViewController:alert animated:YES completion:nil];
        }else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"点击【确认】后，该任务单将通过，是否确认？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self requestForOperationWithStatus:1 withSta_id:model.Id withCk_id:nil];
            }];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:sureAction];
            [alert addAction:cancleAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"点击【确认】后，该任务单将通过，是否确认？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self requestForOperationWithStatus:1 withSta_id:model.Id withCk_id:nil];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

//status类型 1：通过 2：驳回
- (void)requestForOperationWithStatus:(int)status withSta_id:(NSString *)sta_id withCk_id:(NSString *)ck_id {
    [HttpRequest PostWithApi:LogisticsSupplierTaskSure params:@{@"sta_id":sta_id,@"ck_id":ck_id ? ck_id : @"",@"status":@(status)} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已确认"];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

//status类型 1：通过 2：驳回
- (void)requestForBoHuiWithReason:(NSString *)reason {
    [HttpRequest PostWithApi:LogisticsSupplierTaskSure params:@{@"sta_id":@(boHui_task_id),@"status":@(2),@"reject":reason} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已驳回"];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerListCell *cell = [TaskManagerListCell TaskManagerListCellWithTableView:tableView];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    cell.model = model;
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    TaskManagerDetailVC *vc = [TaskManagerDetailVC new];
    vc.sta_id = model.Id;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
